/**
 * GUI - Login
 * @author Mikkel Christiansen
 */

package com.kea.firsthorse.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.kea.firsthorse.shared.FieldVerifier;
import com.kea.firsthorse.shared.Security;
import com.kea.firsthorse.shared.SecurityIface;
import com.kea.firsthorse.shared.User;
import com.sksamuel.jqm4gwt.JQMContext;
import com.sksamuel.jqm4gwt.Mobile;
import com.sksamuel.jqm4gwt.button.JQMButton;
import com.sksamuel.jqm4gwt.form.elements.JQMPassword;
import com.sksamuel.jqm4gwt.form.elements.JQMText;

public class GUI_Login extends GUI_Master implements ClickHandler {

	private JQMText txtUserid;
	private JQMPassword txtPassword;
	private JQMButton btnLogin;

	private final ConnectionServiceAsync greetingService = GWT
			.create(ConnectionService.class);

	public GUI_Login() {
		
		super(false, false);
		
		// Logo
		HTML html = new HTML(
				"<center><img src=\"images/logo.jpg\"></center>");
		add(html);

		txtUserid = new JQMText();
		txtUserid.setText("User ID:");
		add(txtUserid);

		txtPassword = new JQMPassword();
		txtPassword.setText("Password:");
		add(txtPassword);

		btnLogin = new JQMButton("Login");
		btnLogin.addClickHandler(this);
		add(btnLogin);

	}

	@Override
	public void onClick(ClickEvent e) {

		if (e.getSource().equals(btnLogin)) {
			System.out.println("Sending login data");
			sendNameToServer();
		}
	}

	private void sendNameToServer() {
		String textIDToServer = this.txtUserid.getValue();
		System.out.println("txtUserid =" + this.txtUserid.getValue());
		String textPWToServer = this.txtPassword.getValue();
		System.out.println("txtPassword =" + this.txtPassword.getValue());
		if (!FieldVerifier.isValidName(textIDToServer)) {
			txtUserid.setText("indtast venligst et brugerid på > 1 cifre");
			return;
		}
		if (!FieldVerifier.isValidPassword(textPWToServer)) {
			txtPassword.setText("Ikke gyldigt password, min. 5 tegn");
			return;
		}
		
		Mobile.showLoadingDialog("Loading...");
		
		SecurityIface s = new Security();
		String hashedpw = s.hashcrypt(textPWToServer);
		greetingService.greetServer(textIDToServer, hashedpw,
				new AsyncCallback<User>() {

					@Override
					public void onFailure(Throwable caught) {
						txtUserid.setText("Talking to server");
					
					}

					@Override
					public void onSuccess(User result) {
						txtUserid.setText("Talking to server");
						if (result == null) {
							
							//bruger ikke godkendt vi prøver igen...
							GUI_Login gp = new GUI_Login();
							JQMContext.changePage(gp);
						}else{
							//bruger godkendt, vis menuside...
						GUI_Menu menupage = new GUI_Menu(result);
						JQMContext.changePage(menupage);
						}
					}
				});
	}
}